#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QMessageBox

from data_alchemy.user_infor_alchemy import UserInforAlchemy
from init import RUNNING_MODE, TEST_MODE
from initLogger import logger
from ui.loginUI_layout import Ui_Login_Dialog


class LoginDialog(QDialog, Ui_Login_Dialog):
    '''
    类功能：登录对话框类
    '''

    def __init__(self, parent):
        super(LoginDialog, self).__init__()
        #QDialog.__init__(self, parent)

        # 单独移除帮助按钮
        self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)

        self.currentVoucherTextEdit = None


        self.setupUi(self)



    def onLogin(self):
        '''
        函数功能：登录按钮响应函数
        :return:
        '''
        logger.debug("call onLogin function")

        if (RUNNING_MODE==TEST_MODE):
            #测试模式不做登录认证
            self.accept()
            return

        username = self.username_lineEdit.text().strip()
        password = self.password_lineEdit.text()

        logger.debug("login username:%s    password:%s", username, password)

        # 简单的验证
        if not username:
            QMessageBox.warning(self, '输入错误', '请输入用户名!')
            self.username_lineEdit.setFocus()
            return

        if not password:
            QMessageBox.warning(self, '输入错误', '请输入密码!')
            self.password_lineEdit.setFocus()
            return

        # 模拟验证 - 实际应用中应该连接数据库或API
        if self.authenticate(username, password):
            #self.save_settings()
            #QMessageBox.information(self, '登录成功', f'欢迎, {username}!')
            self.accept()  # 关闭对话框并返回 QDialog.Accepted
        else:
            QMessageBox.critical(self, '登录失败', '用户名或密码错误!')
            self.username_lineEdit.clear()
            self.username_lineEdit.setFocus()
            self.password_lineEdit.clear()
            self.password_lineEdit.setFocus()


        # 逻辑详见：I:\anbc_work\code\deepseek_python_20251018_d81af4.py

    def authenticate(self, username, password):
        '''
        函数功能：对账号密码验证
        :return:
        '''



        userInforAlchemy = UserInforAlchemy()
        result = userInforAlchemy.verifyPassword(username, password)
        logger.info(result)
        return result

    def onCancel(self):
        '''
        函数功能：取消按钮响应函数
        :return:
        '''

        logger.debug("call onCancel function")
        reply = QMessageBox.question(self, '确认退出',
                                     '确定要退出登录吗?',
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)


        if reply == QMessageBox.Yes:
            self.reject()

    def rejected(self):
        '''
        函数功能：覆盖右上角关闭按钮
        :return:
        '''

        logger.debug("call Rejected function")
        super(LoginDialog, self).rejected()